package main

import (
	"bufio"
	"fmt"
	"imooc-go-projects/imooc-gointro/pipeline"
	"os"
)

func main() {
	// 这里最终生成的文件会有大小，因此建议git push代码时先删除该文件
	//	filename		数据量(个)		fileSize(byte)
	// large.in			100000000		800000000
	// small.in			64
	const filename  = "large.in"
	const n = 100000000
	file, err := os.Create(filename)
	if err != nil {
		panic(err)
	}
	defer file.Close()
	p := pipeline.RandomSource(n)
	writer := bufio.NewWriter(file)
	pipeline.WriterSink(writer, p)
	writer.Flush()

	file, err = os.Open(filename)
	if err != nil {
		panic(err)
	}
	defer file.Close()

	p = pipeline.ReaderSource(bufio.NewReader(file), -1)

	count := 0
	for v := range p {
		fmt.Println(v)
		count++
		if count >= 100 {
			break
		}
	}
}

func WriteReadDemo() {
	// 这里最终生成的文件会有800M大小，因此建议git push代码时先删除该文件
	const filename  = "large.in"
	const n = 100000000
	file, err := os.Create(filename)
	if err != nil {
		panic(err)
	}
	defer file.Close()
	p := pipeline.RandomSource(n)
	writer := bufio.NewWriter(file)
	pipeline.WriterSink(writer, p)
	writer.Flush()

	file, err = os.Open(filename)
	if err != nil {
		panic(err)
	}
	defer file.Close()

	p = pipeline.ReaderSource_Write_Read(bufio.NewReader(file))

	count := 0
	for v := range p {
		fmt.Println(v)
		count++
		if count >= 100 {
			break
		}
	}
}

func mergeDemo() {
	p := pipeline.Merge(pipeline.InMemoSort(pipeline.ArraySource(3, 2, 6, 7, 4)),
		pipeline.InMemoSort(pipeline.ArraySource(7, 4, 0, 3, 2, 13, 8)))
	// 遍历channel p, 遍历到p末尾时退出(遍历channel时一定要保证channel已关闭)
	//for {
	//	if num, ok := <-p; ok {
	//		fmt.Println(num)
	//	} else {
	//		break
	//	}
	//}

	// 遍历channl p, 遍历到p末尾时自动退出(遍历channel时一定要保证channel已关闭)
	for v := range p {
		fmt.Println(v)
	}
}